<template>
  <!-- 搜索 -->
  <div style="margin-bottom: 5px; display: flex; align-items: center;">
    <el-input v-model="searchForm.eid" suffix-icon="el-icon-search" placeholder="输入编号" style="width: 200px; height: 40px;"></el-input>
    <el-input v-model="searchForm.ename" placeholder="输入姓名" style="width: 200px; height: 40px; margin-left: 10px;"></el-input>
    <el-button style="height: 40px; margin-left: 10px;" @click="handleSearch">查询</el-button>
    <el-button style="height: 40px; margin-left: 10px;" @click="resetSearch">重置</el-button>
    <div style="margin-left: auto; display: flex;">
      <el-button type="primary" style="width: 73px; height: 40px;" @click="resetForm">添加</el-button>
      <el-button style="width: 73px; height: 40px; background: mediumseagreen; color: white; margin-left: 10px;" @click="exportData">导出</el-button>
    </div>
  </div>

  <div>
    <el-table :data="tableData" style="width: 100%" class="el-table" max-height="700">
      <el-table-column label="员工编号" prop="eid"></el-table-column>
      <el-table-column label="姓名" prop="ename"></el-table-column>
      <el-table-column label="级别" prop="elevel"></el-table-column>
      <el-table-column label="电话" prop="etelPhone"></el-table-column>
      <el-table-column label="工资" prop="esalary"></el-table-column>
      <el-table-column label="备注" prop="other"></el-table-column>
      <el-table-column label="操作">
        <!-- 编辑和删除按钮 -->
        <template v-slot="scope">
          <el-button @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除？" @confirm="handleDelete(scope.row.eid)">
            <template v-slot:reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="custom-pagination"
    >
    </el-pagination>
    <!-- 对话框用来编辑和添加 -->
    <el-dialog
        title="提示"
        v-model="dialogVisible"
        width="30%"
        :before-close="handleClose"
        modal-append-to-body
    >
      <!-- 表单-->
      <el-form ref="Reform" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="员工编号" prop="eid">
          <el-input v-model="form.eid" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="ename">
          <el-input v-model="form.ename" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="epas">
          <el-input v-model="form.epas" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="级别" prop="elevel">
          <el-input v-model="form.elevel" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="etelPhone">
          <el-input v-model="form.etelPhone" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="工资">
          <el-input v-model="form.esalary" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.other" style="width: 80%"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="formMode === 'add' ? handleAdd() : handleEditConfirm()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, ref} from 'vue';
import axios from 'axios';
import {ElMessageBox, ElNotification} from 'element-plus';
import 'element-plus/es/components/icon/style/css';

const pageSize = ref(5);
const pageNum = ref(1);
// 用于存储所有数据
const rawData = ref([]);
// 用于存储搜索结果
const searchResults = ref([]);
// 用于显示的数据源
const displayData = computed(() => (searchResults.value.length ? searchResults.value : rawData.value));

// 计算总数
const total = computed(() => displayData.value.length);
const dialogVisible = ref(false);
const formMode = ref('add');
const Reform = ref(null);

// 数据获取
const fetchEmployees = async () => {
  try {
    const response = await axios.get("http://localhost:8089/emps");
    rawData.value = response.data.data;
  } catch (error) {
    ElNotification.error('加载员工数据失败');
  }
};
fetchEmployees();

// 表单数据
const form = ref({
  eid: '',
  ename: '',
  epas: '',
  elevel: '',
  etelPhone: '',
  esalary: '',
  other: '',
});

const searchForm = ref({
  eid: '',
  ename: '',
});

// 重置表单
const resetForm = () => {
  form.value = {
    eid: '',
    ename: '',
    epas: '',
    elevel: '',
    etelPhone: '',
    esalary: '',
    other: '',
  };
  dialogVisible.value = true; // 打开对话框
  formMode.value = 'add'; // 设置模式为添加
};

// 表单验证规则
const validateNumber = (rules, value, callback) => {
  const reg = /^\d+$/;
  if (!reg.test(value)) {
    callback(new Error('请输入数字'));
  } else {
    callback();
  }
};
const rules = {
  eid: [
    {required: true, message: '请输入员工编号', trigger: 'blur'},
    {validator: validateNumber, trigger: 'blur'},
  ],
  ename: [
    {required: true, message: '请输入名字', trigger: 'blur'},
  ],
  epas: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {max: 12, message: '密码长度不能超过12位', trigger: 'blur'},
  ],
  elevel: [
    {required: true, message: '请输入级别', trigger: 'blur'},
  ],
  etelPhone: [
    {required: true, message: '请输入电话号码', trigger: 'blur'},
    {min: 11, max: 11, message: '号码必须为11位', trigger: 'blur'},
    {validator: validateNumber, trigger: 'blur'},
  ],
};

// 分页处理
const tableData = computed(() => {
  console.log("searchResults.value", searchResults.value);
  if (searchResults.value.length) {
    const startIdx = (pageNum.value - 1) * pageSize.value;
    const endIdx = startIdx + pageSize.value;
    return searchResults.value.slice(startIdx, endIdx);
  } else {
    const startIdx = (pageNum.value - 1) * pageSize.value;
    const endIdx = startIdx + pageSize.value;
    return rawData.value.slice(startIdx, endIdx);
  }
});

const handleSizeChange = (val) => {
  pageSize.value = val;
  pageNum.value = 1; // 重置为第一页
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
};

// 处理添加
const handleAdd = () => {
  Reform.value.validate(async (valid) => {
    if (valid) {
      try {
        await axios.post('http://localhost:8089/emps/add', form.value);
        rawData.value.push(form.value);
        ElNotification.success('添加成功');
        dialogVisible.value = false;
      } catch (error) {
        ElNotification.error('添加失败');
      }
    } else {
      ElNotification.error('请修正表单中的错误');
    }
  });
};

const handleClose = () => {
  ElMessageBox.confirm('确认关闭？')
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {
      });
};

// 处理编辑
const handleEdit = (row) => {
  Object.assign(form.value, row); // 直接将 row 数据赋值到 form 中
  dialogVisible.value = true;
  formMode.value = 'edit';
};

const handleEditConfirm = () => {
  // 确保 Reform 引用的是模板中定义的表单实例
  if (Reform.value && Reform.value.validate) {
    Reform.value.validate(async (valid) => {
      if (valid) {
        try {
          await axios.put('http://localhost:8089/emps/update', form.value);
          const index = rawData.value.findIndex((item) => item.eid === form.value.eid);
          if (index !== -1) {
            rawData.value[index] = { ...form.value };
            ElNotification.success('编辑成功');
            dialogVisible.value = false;
            formMode.value = 'add';
          }
        } catch (error) {
          ElNotification.error('编辑失败');
        }
      } else {
        ElNotification.error('请修正表单中的错误');
      }
    });
  } else {
    console.error('表单实例不存在或未正确初始化');
  }
};


// 处理删除
const handleDelete = async (eid) => {
  if (eid === "001") {
    ElNotification.warning("无法删除001号员工");
    return;
  }
  try {
    await axios.delete(`http://localhost:8089/emps/${eid}`);
    const index = rawData.value.findIndex((item) => item.eid === eid);
    if (index !== -1) {
      rawData.value.splice(index, 1);
      ElNotification.success('删除成功');
    }
  } catch (error) {
    ElNotification.error('删除失败');
  }
};

const handleSearch = async () => {
  try {
    const id = searchForm.value.eid;
    const name = searchForm.value.ename;
    let response;

    if (id && name) {
      response = await axios.post(`http://localhost:8089/emps/searchEmpByIdAndName/${id}/${name}`);
    } else if (id) {
      response = await axios.post(`http://localhost:8089/emps/getEmpById/${id}`);
    } else if (name) {
      response = await axios.post(`http://localhost:8089/emps/getEmpByEname/${name}`);
    } else {
      ElNotification.error('搜索条件不完整');
      return;
    }

    // 检查响应数据结构
    console.log("响应数据: ", response.data);

    const data = response.data.data ?? [];
    if (data.length === 0) {
      ElNotification.warning('未找到符合条件的员工');
    }

    searchResults.value = data;
    pageNum.value = 1; // 重置分页到第一页
  } catch (error) {
    ElNotification.error('搜索失败：' + error.message);
  }
};

// 重置搜索
const resetSearch = () => {
  searchResults.value = [];
  searchForm.value = {eid: '', ename: ''};
  pageNum.value = 1;
};

const jsonToCsv = (data) => {
  const csvRows = [];
  const headers = Object.keys(data[0]);
  csvRows.push(headers.join(','));

  for (const row of data) {
    const values = headers.map(header => {
      const escaped = ('' + row[header]).replace(/"/g, '\\"');
      return `"${escaped}"`;
    });
    csvRows.push(values.join(','));
  }

  return csvRows.join('\n');
};

//导成csv表
const exportData = () => {
  const data = displayData.value;
  if (data.length === 0) {
    ElNotification.warning('没有数据可导出');
    return;
  }
  const csvData = jsonToCsv(data);
  const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', '员工表.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.custom-pagination {
  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(5px);
  padding: 10px;
  border-radius: 5px;
}

.el-table {
  background: rgba(211, 211, 211, 0.4);
  backdrop-filter: blur(4px);
  border-radius: 5px;
}
</style>
